package com.swpu.filter;

import com.swpu.common.Constants;
import com.swpu.exception.BusinessException;
import com.swpu.model.entity.SysUser;
import com.swpu.result.ResultCode;
import com.swpu.service.SysUserService;
import com.swpu.utils.ResponseUtils;
import com.swpu.utils.TokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT token 过滤器
 *
 * @author haoxr
 * @since 2023/9/13
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {
    @Resource
    private SysUserService sysUserService;


    /**
     * 从请求中获取 JWT Token，校验 JWT Token 是否合法
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean isNeedLogin = !(request.getRequestURI().contains("/login")||request.getRequestURI().contains("/register")||request.getRequestURI().contains("/captcha")||request.getRequestURI().contains("/rsa-pks"));
        if(isNeedLogin) {
            boolean checkUserId = checkUserId(response);
            if(checkUserId) {
                filterChain.doFilter(request, response);
            }
            else {
                ResponseUtils.writeErrMsg(response, ResultCode.ACCESS_UNAUTHORIZED);
            }
        }else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 检查登录用户的ID
     *
     */
    private boolean checkUserId(HttpServletResponse response) throws IOException {
        String userId = getCurrentUserId(response);
        if(userId==null){
            return false;
        }
        SysUser user = sysUserService.selectById(userId);
        return user != null;
    }

    public String getCurrentUserId(HttpServletResponse response) throws IOException {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(Constants.TOKEN_KEY);
        String userId = TokenUtil.verifyToken(token);
        return userId;
    }
}
